<template>
    <div class="search">
        <mt-search v-model="searchKey"></mt-search>
        <mt-button size="small" class="btn" @click='searchProduct'>搜索</mt-button>
        <mt-cell :to="{'name': 'SearchList', params: {'key': value}}" :title="value" v-for="(value,index) in historyArr" :key='index'><span @click.prevent.stop="delhistory(index)">x</span></mt-cell>
        <span v-show="historyArr.length===0">没有数据</span>
    </div>
</template>

<script>
export default {
  data () {
    return {
      searchKey: '',
      historyArr: []
    }
  },
  methods: {
    // 跳转到商品详情页

    searchProduct () {
      var temp = this.gethistory()
      // 加入当前搜索内容
      temp.unshift(this.searchKey)
      // 本地存储起来
      localStorage.setItem('history', JSON.stringify(temp))
      // 路由跳转   如果是通过path定义跳转需要注意的是参数需要拼接
      this.$router.push({'path': '/searchList/' + this.searchKey})
    },
    // 获取本地存储方法的封装
    gethistory () {
      var historyStr = localStorage.getItem('history')
      return JSON.parse(historyStr || '[]')
    },
    // 删除某条记录
    delhistory (index) {
      this.historyArr = this.gethistory()
      this.historyArr.splice(index, 1)
      localStorage.setItem('history', JSON.stringify(this.historyArr))
    }
  },
  mounted () {
    // 设置头部标题
    this.$store.state.title = '搜索中心'
    // 读取当前本地存储数据
    this.historyArr = this.gethistory()
  }
}
</script>

<style lang='scss' scoped>
.search {
  position: relative;
  .mint-search {
    height: auto;
  }
  .btn{
      position: absolute;
      height: 28px;
      top: 8px;
      right: 0;
      background-color: skyblue;
      z-index: 999;
  }
}
</style>
